#include "window.h"
#include "ui_window.h"

window::window(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::windowClass)
{
    ui->setupUi(this);
    setWindowTitle("HTTPSrv by Alex Snet");
    loadValues();
}

window::~window()
{
    saveValues();
    delete ui;
}

void window::on_browse_clicked()
{
    QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly;
    QString directory = QFileDialog::getExistingDirectory(this,tr("Choose root folder for HTTPSrv"),ui->path->text(),options);
    if (!directory.isEmpty())
    {
        ui->path->setText( directory );
    }
}

void window::on_start_clicked()
{
    serverStart();
}
void window::on_restart_clicked()
{
    serverStop();
    serverStart();
}
void window::on_stop_clicked()
{
    serverStop();
}
void window::serverStart()
{
    bool listening = server.listen( QHostAddress::Any, ui->port->value() );
    if(!listening) {
        qDebug("Bad.. Server doesn't start!");
    } else {
        ui->restart->setEnabled( true );
        ui->stop->setEnabled( true );
        ui->start->setEnabled( false );
    }
    server.setPath( ui->path->text() );
    server.setBandwidth( ui->uploadLimit->value(), ui->downloadLimit->value() );
    connect( &server, SIGNAL(clientCountChanged(int)), this, SLOT(clientCountChanged(int)) );
}
void window::serverStop()
{
    server.close();
    ui->start->setEnabled( true );
    ui->restart->setEnabled( false );
    ui->stop->setEnabled( false );
    disconnect( &server, SIGNAL(clientCountChanged(int)), this, SLOT(clientCountChanged(int)) );
}


void window::loadValues()
{
    ui->path->setText( setts.value("/window/path", QDir::currentPath() ).value<QString>() );
    ui->port->setValue( setts.value("/window/port", 8181).value<int>() );

    ui->uploadLimit->setValue( setts.value("/bandwidth/upload", 2048).value<int>() );
    ui->downloadLimit->setValue( setts.value("/bandwidth/download", 2048).value<int>() );

    this->resize( setts.value("/window/size",QSize(100,100)).value<QSize>() );
    this->move( setts.value("/window/pos",QPoint(100,100)).value<QPoint>() );
}
void window::saveValues()
{
    setts.setValue("/window/path", ui->path->text() );
    setts.setValue("/window/port", ui->port->value() );

    setts.setValue("/bandwidth/upload",  ui->uploadLimit->value() );
    setts.setValue("/bandwidth/download", ui->downloadLimit->value() );

    setts.setValue("/window/size", this->size() );
    setts.setValue("/window/pos", this->pos() );
}

void window::clientCountChanged(int count)
{
    ui->connections->display( count );
}
